<template>
	<layout :footerVisible="true">
		<view class="h-fill">
			<u-navbar title="会员卡" titleColor="#fff" backIconColor="#fff" :background="navBg"></u-navbar>
			<view>
				<view>
					<view class="">
						<u-swiper :list="vipCardImgs" bgColor="rgba(0,0,0,0)" :autoplay="false" imgMode="aspectFit" :effect3d="true"
						 @change="handleSwiperChange" :height="swiperHeight"></u-swiper>
					</view>
					<view v-if="vipCards.length" class="pad-l-base text-red" style="font-size: 46rpx;">
						￥{{vipCards[cardIdx].price || '0'}}
					</view>
				</view>
				<view class="gap"></view>
				<view class="vip-symbol pad uni-flex align-center">
					<image class="vip-symbol-icon" src="static/img/ic_huiyuan_quanyi@2x.png"></image>
					<text class="vip-symbol-title uni-flex-extend">会员权益</text>
					<text class="vip-symbol-subtitle">彰显会员特权，体现会员个性</text>
				</view>
				<view class="rights-wrapper" v-show="cardIdx == index" v-for="(item, index) in rights" :key="item.id">
					<view class="uni-flex rights" v-for="(right, rightIdx) in item" :key="rightIdx">
						<view class="rights-title">
							<image mode="aspectFit" src="static/img/ic_zhuangshi_tiao@2x.png"></image>
							<text>{{rightIdx + 1}}</text>
						</view>
						<view class="uni-flex-extend rights-text" style="line-height: 42rpx;">{{right}}</view>
					</view>
				</view>
				<view v-if="vipCards.length && vipCards[cardIdx].serviceCount" class="service-count uni-flex">
					<text>联盟门店服务</text>
					<text class="count">{{vipCards[cardIdx].serviceCount}}</text>家
					<view class="l-mg">
						<u-button @click="navToService" shape="circle" size="mini">查看</u-button>
					</view>
				</view>
			</view>
		</view>
		<view slot="footer" class="fill">
			<view v-if="vipCards.length" class="v-fill h-box pad-l-base text-red bot-toolbar">
				<text class="flex-extend" style="font-size: 30rpx;">￥{{vipCards[cardIdx].price}}</text>
						<!-- #ifdef MP-WEIXIN  -->
				<view @click="handleBuy" class="btn-open h-box justify-center" :class="{'btn-open-disabled': !canBuy}">{{btnText}}</view>
						<!-- #endif -->
								<!-- #ifdef MP-TOUTIAO  -->
				<view @click="handleBuyTt" class="btn-open h-box justify-center" :class="{'btn-open-disabled': !canBuy}">{{btnText}}</view>
						<!-- #endif -->
			</view>
		</view>
		<u-popup v-model="visible" mode="center" width="600" height="300">
			<view class="simple-card h-box justify-center v-fill">
				<get-phone-button text="" @change="handleMobileChange">
					<nice-red-button text="绑定手机"></nice-red-button>
				</get-phone-button>
			</view>
		</u-popup>
	</layout>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		genOpenVipOrder,
		genPayInfo,
		getOrderDetail,
		genPayInfoTt
	} from "../api/platform/order.js"
	import {
		getUserInfo,
		getVipCardList
	} from "../api/platform/user.js"
	const ratio = 1.8
	export default {
		data() {
			return {
				navBg: {
					'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)'
				},
				swiperHeight: 0,
				vipCards: [],
				vipCardImgs: [],
				cardIdx: 0,
				order: null,
				orderPayInfo: null,
				rights: [],
				needLoadRemainTimes: false, //是否加载会员剩余的服务次数
				visible: false,
				onlySuperVip: false, //只展示超级vip卡
				serviceCount: 0
			}
		},
		created() {
			let sysInfo = uni.getSystemInfoSync();
			this.swiperHeight = 750 / ratio;
		},
		onLoad(e) {
			if (e.onlySuperVip) {
				this.onlySuperVip = true
			}
		},
		onReady() {
			this.loadData()
		},
		async onPullDownRefresh() {
			await this.loadData()
			uni.stopPullDownRefresh()
		},
		computed: {
			...mapState(['userInfo']),
			isNormalStoreVip() {
				return this.userInfo && this.userInfo.vipInfo && this.userInfo.vipInfo.storeVipCardInfo && this.userInfo.vipInfo.storeVipCardInfo.expirationTime >= Date.now()
			},
			isSuperVip() {
				return this.isNormalStoreVip && this.userInfo.vipInfo.storeVipCardInfo.settlementWay === 'time'
			},
			isMerchantVip() {
				return this.userInfo && this.userInfo.vipInfo && this.userInfo.vipInfo.merchantVipCardInfo && this.userInfo.vipInfo.merchantVipCardInfo.expirationTime >= Date.now()
			},
			btnText() {
				let vipCard = this.vipCards[this.cardIdx]
				if (this.isSuperVip) {
					if (vipCard.type === 'store' && vipCard.settlementWay !== 'time') {
						return '不可购买'
					}
				}
				if (this.isNormalStoreVip) {
					if (vipCard.type === 'store') {
						if (vipCard.level < this.userInfo.vipInfo.storeVipCardInfo.level) {
							return '不可购买'
						} else if (vipCard.level === this.userInfo.vipInfo.storeVipCardInfo.level) {
							return '续费'
						} else {
							return '升级'
						}
					}
				}
				if (this.isMerchantVip) {
					if (vipCard.type === 'merchant') {
						return '续费'
					}
				}
				return '立即开通'
			},
			serviceCountVisible() {
				if (this.vipCards.length > 0) {
					let card = this.vipCards[this.cardIdx]
					return (card.settlementWay === 'time' 
						&& card.time === 'oneYear')
						|| card.type === 'merchant'
				}
			},
			canBuy() {
				if (!this.vipCards.length) {
					return false
				}
				let vipCard = this.vipCards[this.cardIdx]
				if (vipCard.type === 'store') {
					if (this.isSuperVip && vipCard.settlementWay !== 'time') {
						return false
					}
					if (this.isNormalStoreVip && vipCard.level < this.userInfo.vipInfo.storeVipCardInfo.level) {
						return false
					}
				}
				return true
			}
		},
		methods: {
			...mapMutations(["updateUserInfo"]),
			handleView() {
				let card = this.vipCards[this.cardIdx];
				uni.navigateTo({
					url: `../shop/list-level?level=${card.level}`
				})
			},
			handleSwiperChange(index) {
				this.cardIdx = index;
				// this.updateBtnText();
			},
			updateBtnText() {
				let card = this.vipCards[this.cardIdx]
				if (this.userInfo.level.levelValue == card.level) {
					this.btnText = "续期";
				} else {
					this.btnText = "购买";
				}
				this.needLoadRemainTimes = this.userInfo.level.levelValue === card.level;
			},
			navToService() {
				let vipCard = this.vipCards[this.cardIdx]
				if (vipCard.type == 'store') {
					uni.navigateTo({
						url: `../pagesService/map`
					})
				} else {
					if (vipCard.serviceCategoryIds && vipCard.serviceCategoryIds.length) {
						uni.navigateTo({
							url: `../pagesService/map?categoryId=${vipCard.serviceCategoryIds[0]}`
						})
					} else {
						uni.navigateTo({
							url: `../pagesService/map`
						})
					}
				}
			},
			handleCancelPay() {
				uni.showModal({
					title: "您还可以去我的订单进行支付哟",
					cancelText: "回到主页",
					confirmText: "我的订单",
					success: (res => {
						if (res.confirm) {
							uni.switchTab({
								url: "product-list",
								complete: () => {
									uni.navigateTo({
										url: "../pagesFoo/order/order"
									})
								}
							})
						} else {
							uni.switchTab({
								url: "product-list"
							})
						}
					})
				})
			},
			handlePayFailed(msg) {
				uni.showModal({
					title: msg,
					cancelText: "放弃",
					confirmText: "重新支付",
					success: (res) => {
						if (res.confirm) {
							this.handlePay();
						} else {
							this.handleCancelPay();
						}
					}
				})
			},
			navToProductDetail(item) {
				uni.navigateTo({
					url: "../pagesGroup/product-detail?groupId=" + item.id
				})
			},
			handleMobileChange() {
				this.visible = false
				this.handleBuy()
			},
			
			async handleBuyTt(){
				if (!this.canBuy) {
					return
				}
				uni.showLoading({
					mask: true
				})
				try {
					let currentRegion = uni.getStorageSync('currentRegion')
					let currentCityCode = currentRegion.city.value
					let userInfo = await getUserInfo({}, "tt",currentCityCode)
					this.updateUserInfo(userInfo)
					let vipCard = this.vipCards[this.cardIdx];
					console.log(this.order)
					if (!this.order) {
						this.order = await genOpenVipOrder({
							vipCardId: vipCard._id,
							payType:"tt",
							showLoading: false
						})
					}
					if (!this.orderPayInfo) {
						this.orderPayInfo = await genPayInfo({
							orderId: this.order._id,
							payType:"tt",
							showLoading: false
						});
						
					}
					uni.showLoading({
						mask: true,
						title: '检测支付环境'
					})
					
					
					tt.pay({
						orderInfo: {
							order_id: this.orderPayInfo.data.data.order_id,
							order_token: this.orderPayInfo.data.data.order_token
						},
						service: 5,
							success: (res) => {
								console.log('支付成功', res)
								uni.hideLoading()
								this.finishPay("tt")
							},
							fail: (err) => {
								console.log('用户取消支付', err)
								uni.hideLoading()
							}
					})
					
				} catch (e) {
					console.error(e)
					uni.hideLoading()
				}
			},
			async handleBuy() {
				if (!this.canBuy) {
					return
				}
				uni.showLoading({
					mask: true
				})
				try {
					let currentRegion = uni.getStorageSync('currentRegion')
					let currentCityCode = currentRegion.city.value
					let userInfo = await getUserInfo({}, currentCityCode)
					this.updateUserInfo(userInfo)
					let vipCard = this.vipCards[this.cardIdx];
					if (!this.order) {
						this.order = await genOpenVipOrder({
							vipCardId: vipCard._id,
							showLoading: false
						})
					}
					console.log('orderPayInfo1', this.orderPayInfo)
					if (!this.orderPayInfo) {
						this.orderPayInfo = await genPayInfo({
							orderId: this.order._id,
							showLoading: false
						});
					}
					console.log('orderPayInfo2', this.orderPayInfo)
					uni.showLoading({
						mask: true,
						title: '检测支付环境'
					})
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: this.orderPayInfo.timeStamp,
						nonceStr: this.orderPayInfo.nonceStr,
						package: this.orderPayInfo.package,
						signType: this.orderPayInfo.signType,
						paySign: this.orderPayInfo.paySign,
						success: async (res) => {
							console.log('支付成功', res)
							uni.hideLoading()
							this.finishPay()
						},
						fail: (err) => {
							console.log('用户取消支付', err)
							uni.hideLoading()
						}
					})
				} catch (e) {
					console.error(e)
					uni.hideLoading()
				}
			},
			async finishPay(type) {
				try {
					let order = await getOrderDetail({
						id: this.order._id,
						type:type
					})
					if (order.status === 5) {
						let currentRegion = uni.getStorageSync('currentRegion')
						let currentCityCode = currentRegion.city.value
						let userInfo = await getUserInfo({},type,currentCityCode)
						this.updateUserInfo(userInfo)
						let vipCard = this.vipCards[this.cardIdx];
						uni.showModal({
							content: `恭喜您已成为${vipCard.name}会员了`,
							cancelText: '用户中心',
							confirmText: '我的权益',
							success: (res) => {
								if (res.confirm) {
									uni.redirectTo({
										url: "./vip-rights"
									})
								} else {
									uni.switchTab({
										url: "../pages/user/user"
									})
								}
							}
						})
					}
				} catch (e) {
					console.error(e)
					uni.showModal({
						content: '查询支付状态遇到错误！',
						cancelText: '联系客服',
						confirmText: '重试',
						success: (res) => {
							if (res.confirm) {
								this.finishPay()
							} else {
								this.$copy("i3d008", () => {
									uni.showModal({
										content: '客服微信已复制，请添加客服好友',
										showCancel: false,
										confirmText: '朕知道了'
									})
								})
							}
						}
					})
				}
			},
			async loadData() {
				uni.showLoading({
					mask: true
				})
				try {
					this.order = null;
					
					var res = await getVipCardList({
						showLoading: true,
						cityCode: uni.getStorageSync('currentRegion').city.value
					})
					if (this.onlySuperVip) {
						let list = res.filter(item => {
							return item.settlementWay === 'time' && item.time === 'oneYear'
						})
						if (list.length) {
							res = list
						}
					}
					let imgs = []
					let rights = []
					res.forEach(item => {
						item.price = item.price / 100
						imgs.push({
							image: item.imageUrl
						})
						rights.push(item.rights.split("\n"))
					})
					this.vipCardImgs = imgs
					this.rights = rights
					this.vipCards = res
					uni.hideLoading()
				} catch (e) {
					console.error(e)
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FFFFFF;
	}

	.group-price-flag {
		width: 125rpx;
		height: 50rpx;
		background-image: url(../pagesGroup/static/img/ic_bg_di@2x.png);
		background-size: 100% 100%;
		color: #FFFFFF;
		line-height: 50rpx;
		text-align: center;
		padding-left: 10rpx;
		font-size: 24rpx;
	}

	.vip-symbol {
		&-icon {
			width: 80rpx;
			height: 80rpx;
			margin-right: 20rpx;
		}

		&-title {
			color: #966200;
			font-size: 36rpx;
			font-weight: bold;
		}

		&-subtitle {
			color: #D89D4D;
		}
	}

	.rights-wrapper {
		padding: 10rpx 20rpx 20rpx 30rpx;
	}

	.rights {
		&-title {
			position: relative;
			margin-right: 30rpx;
			width: 60rpx;
			height: 60rpx;

			image {
				width: 100%;
				height: 100%;
			}

			text {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				color: #966200;
			}
		}

		&-text {
			color: #666666;
		}
	}

	.rights:not(:last-child) {
		margin-bottom: 24rpx;
	}

	.list {
		padding-bottom: 120rpx;
	}

	.btn-buy {
		background-color: #FF7E00;
		color: #fff;
		border-radius: 20px;
		padding: 0 20px;
		width: 400rpx;
	}

	.btn-check {
		border: 1px solid #CCCCCC;
		border-radius: 20rpx;
		padding: 0 20rpx;
		font-size: 20rpx;
		margin-left: 20rpx;
	}

	.vip-card {
		width: 100%;
		height: 100%;
		position: relative;
		color: #fff;
		font-weight: bold;

		&-bg {
			position: absolute;
			left: 20px;
			right: 20px;
			top: 20px;
			bottom: 20px;
			border-radius: 20rpx;
		}

		&-name {
			position: absolute;
			top: 40px;
			left: 80px;
			font-size: 50rpx;
		}

		&-price {
			position: absolute;
			bottom: 40px;
			right: 80px;

			&-symbol {
				font-size: 30rpx;
				margin-right: 10px;
			}

			&-num {
				font-size: 50rpx;
			}
		}
	}

	.service-count {
		padding-left: 120rpx;
		padding-bottom: 20rpx;
		color: #666666;

		.count {
			color: #FF7E00;
		}
	}

	.p-content {
		padding-bottom: 140rpx;
	}

	.buy-info {
		color: #fff;
		height: 120rpx;

		&-btn-alone {
			height: 100%;
			background-color: #FFA1B5;
			justify-content: center;
		}

		&-btn-group {
			height: 100%;
			background-color: #D61719;
			justify-content: center;
		}
	}

	.main-price {
		line-height: 20px;
		color: #D61719;
		margin-right: 8rpx;
	}

	.btn-open {
		width: 375rpx;
		height: 100%;
		background: #D61719;
		color: #FFFFFF;
		font-size: 34rpx;
	}
	.btn-open-disabled {
		background: #999;
	}
</style>
